<template>
  <div class="basic-content">
    <el-descriptions title="资质认证" />
    <el-form
      ref="ruleFormRef"
      label-position="top"
      :model="ruleForm"
      :rules="rules"
      class="basic-form"
      label-width="auto"
    >
      <el-form-item prop="license">
        <el-upload
          class="upload-demo"
          drag
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-change="
            (response, uploadFile) =>
              handleAvatarChange(response, uploadFile, 'workplace')
          "
          :on-success="
            (response, uploadFile) =>
              handleAvatarSuccess(response, uploadFile, 'workplace')
          "
          :before-upload="rawFile => beforeAvatarUpload(rawFile, 'workplace')"
          :limit="1"
          accept="image/png, image/jpeg, image/jpg"
          multiple
        >
          <img
            v-if="imageItem.workplace"
            :src="imageItem.workplace"
            class="avatar"
          />
          <div v-else>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              <el-text size="large" type="primary">*办公场所照片</el-text>
              <el-text size="small"
                >支持 JPG, PNG 格式，文件大小不超过 5MB</el-text
              >
            </div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item prop="license">
        <el-upload
          class="upload-demo"
          drag
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-change="
            (response, uploadFile) =>
              handleAvatarChange(response, uploadFile, 'reception')
          "
          :on-success="
            (response, uploadFile) =>
              handleAvatarSuccess(response, uploadFile, 'reception')
          "
          :before-upload="rawFile => beforeAvatarUpload(rawFile, 'reception')"
          :limit="1"
          accept="image/png, image/jpeg, image/jpg"
          multiple
        >
          <img
            v-if="imageItem.reception"
            :src="imageItem.reception"
            class="avatar"
          />
          <div v-else>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              <el-text size="large" type="primary"
                >*公司前台照片（包含logo）</el-text
              >
              <el-text size="small"
                >支持 JPG, PNG 格式，文件大小不超过 5MB</el-text
              >
            </div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item prop="license">
        <el-upload
          class="upload-demo"
          drag
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-change="
            (response, uploadFile) =>
              handleAvatarChange(response, uploadFile, 'license')
          "
          :on-success="
            (response, uploadFile) =>
              handleAvatarSuccess(response, uploadFile, 'license')
          "
          :before-upload="rawFile => beforeAvatarUpload(rawFile, 'license')"
          :limit="1"
          accept="image/png, image/jpeg, image/jpg"
          multiple
        >
          <img
            v-if="imageItem.license"
            :src="imageItem.license"
            class="avatar"
          />
          <div v-else>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              <el-text size="large" type="primary">*开户许可证</el-text>
              <el-text size="small"
                >支持 JPG, PNG 格式，文件大小不超过 5MB</el-text
              >
            </div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item prop="license">
        <el-upload
          class="upload-demo"
          drag
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-change="
            (response, uploadFile) =>
              handleAvatarChange(response, uploadFile, 'description')
          "
          :on-success="
            (response, uploadFile) =>
              handleAvatarSuccess(response, uploadFile, 'description')
          "
          :before-upload="rawFile => beforeAvatarUpload(rawFile, 'description')"
          :limit="1"
          accept="image/png, image/jpeg, image/jpg"
          multiple
        >
          <img
            v-if="imageItem.description"
            :src="imageItem.description"
            class="avatar"
          />
          <div v-else>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              <el-text size="large" type="primary">*业务说明</el-text>
              <el-text size="small"
                >支持 JPG, PNG 格式，文件大小不超过 5MB</el-text
              >
            </div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item prop="license">
        <el-upload
          class="upload-demo"
          drag
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="false"
          :on-change="
            (response, uploadFile) =>
              handleAvatarChange(response, uploadFile, 'other')
          "
          :on-success="
            (response, uploadFile) =>
              handleAvatarSuccess(response, uploadFile, 'other')
          "
          :before-upload="rawFile => beforeAvatarUpload(rawFile, 'other')"
          :limit="1"
          accept="image/png, image/jpeg, image/jpg"
          multiple
        >
          <img v-if="imageItem.other" :src="imageItem.other" class="avatar" />
          <div v-else>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              <el-text size="large" type="primary"
                >上传其他资料
                (营业执照盖章扫描件、法人证件盖章扫描件、联系人证件盖章扫描件、其他资质证件)</el-text
              >
              <el-text size="small"
                >支持 JPG, PNG 格式，文件大小不超过 5MB</el-text
              >
            </div>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { UploadFilled } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";
import { message } from "@/utils/message";
import { useVerifyCode } from "../verifyCode";
const { isDisabled, text } = useVerifyCode();
interface RuleForm {
  name: string;
  mobile: string;
  idCard: string;
  cardType: string;
  referral: string;
  verifyCode: string;
  address: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  name: "",
  mobile: "",
  idCard: "",
  cardType: "",
  address: "",
  verifyCode: "",
  referral: ""
});
const imageFrontUrl = ref("");
const imageBackUrl = ref("");

const imageItem = reactive({
  workplace: "",
  reception: "",
  license: "",
  description: "",
  other: ""
});

const rules = reactive<FormRules<RuleForm>>({});

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile: any,
  customParam?: string
) => {
  // 优先使用 raw 文件，如果没有则使用 url
  if (uploadFile.raw) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
  } else if (uploadFile.url) {
    imageUrl.value = uploadFile.url;
  }
};

const handleAvatarChange = (
  response: any,
  uploadFile: any,
  customParam?: string
) => {
  if (customParam === "idCardFront") {
    if (uploadFile.raw) {
      imageFrontUrl.value = URL.createObjectURL(uploadFile.raw);
    }
  } else if (customParam === "idCardBack") {
    if (uploadFile.url) {
      imageBackUrl.value = uploadFile.url;
    }
  }
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (
  rawFile: any,
  customParam?: string
) => {
  console.log("beforeUpload triggered:", rawFile);

  const fileType = ["image/png", "image/jpeg", "image/jpg"];
  if (!fileType.includes(rawFile.type)) {
    message("上传的图片只能是 JPG, PNG, JPEG格式", { type: "warning" });
    return false;
  } else if (rawFile.size / 1024 / 1024 > 5) {
    message("上传的图片必须小于5M", { type: "warning" });
    return false;
  }
  // 直接在这里创建 URL，确保有文件对象
  if (rawFile) {
    imageItem[`${customParam}`] = URL.createObjectURL(rawFile);
  }

  return true;
};
</script>

<style lang="scss" scoped>
.basic-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .el-form-item {
    width: 48%;
    margin-bottom: 20px;
  }
  .upload-item {
    width: 100%;
  }
  .upload-demo {
    width: 100%;
    .el-upload__text {
      display: flex;
      flex-direction: column;
    }
    .avatar {
      height: 100px;
    }
  }
}
</style>
